/**
 * UserController
 *
 * @description :: Server-side logic for managing users
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

var crypto = require('crypto');
module.exports = {
  'login': function (req, res, next) {
		if (req.method === "POST") {
			var username = req.param("username", "");
			var password = req.param("password", "");

			if (!username || !password) {
				req.session.flash = {
					error: "用户名、密码不能为空！"
				};
				return res.redirect("back");
			}
			User.findOne({
				username: username
			}).populate('usergroup').exec(function findOneCB(err, found) {
				if (err) {
					return next(err);
				}
				if (!found) {
					req.session.flash = {
						error: "用户不存在！"
					}
					return res.redirect("back");
				}
				if (!found.usergroup||!found.usergroup.purview) {
					req.session.flash = {
						error: "您或您所在组被禁用"
					}
					return res.redirect("back");
				}
				var md5 = crypto.createHash('md5');
				md5.update(password);
				var passwordHash = md5.digest("hex");
				if (passwordHash != found.password) {
					req.session.flash = {
						error: "用户名或者密码错误！"
					}
					return res.redirect("back");
				}
				req.session.user = found;
				return res.redirect("/user");
			});
		} else {
			res.locals.layout=false
			return res.view();
		}
  },
  'index': function (req, res, next) {
		res.locals.layout='user/layout'
		return res.view();
  },
  'profile': function (req, res, next) {
		res.locals.layout='user/layout'
		return res.view();
  },
  'onlyadmin': function (req, res, next) {
		res.end('onlyadmin');
  }
};

